<template>
  <div class="music-player-mini">
    <div class="container">
      <!-- 歌曲图片 -->
      <div class="song-img" @click="showPlayerPage">
        <img :src="song.imgUrl" :style="{animationPlayState: imgRun,WebkitAnimationPlayState: imgRun}">
      </div>
      <!-- 播放器中间部分：进度、时间、控制功能 -->
      <div class="middle">
        <div class="progress">
          <span class="current-progress" :style="{width: currProgress}"></span>
        </div>
        <div class="bottom">
          <div class="info">{{getSongAndSingersName}}</div>
          <div class="control">
            <span class="prev" @click="playPrev"></span>
            <span :class="playStyle" @click="playOrPause"></span>
            <span class="next" @click="playNext"></span>
          </div>
        </div>

      </div>
      <!-- 当前歌曲所在的歌曲列表 -->
      <div class="list" @click="showCurrList"></div>
      <transition name="curlist">
        <curr-song-list v-show="showList"></curr-song-list>
      </transition>

      <!-- 音乐 -->
      <audio id="main-audio" class="music-audio" :src="song.url" ref="audio"></audio>

    </div>
  </div>
</template>

<script>
  import CurrSongList from "./CurrSongList";
  export default {
    name: "MusicPlayerMini",
    components: {
      CurrSongList
    },
    data(){
      return {
        controlLock: true,
        isPlay: true,
        currProgress: '0%'
      };
    },
    computed: {
      showList(){
        return this.$store.getters.currSongListVisible;
      },
      playStyle(){
        if(this.isPlay){
          return "stop";
        }else{
          return "play";
        }
      },
      imgRun(){
        if (this.isPlay){
          return 'running'
        }else{
          return 'paused';
        }
      },
      song(){
        return this.$store.getters.song;
      },
      getSongAndSingersName(){
        // let arr = this.song.singers.map(item => {
        //   return item.name;
        // });
        // return this.song.name + '-' + arr.join('&');
        let arr = [];
        for (let i=0;i<this.song.singers.length;i++){
          arr.push(this.song.singers[i].name);
        }
        let str = arr.toString();
        return this.song.name + '-' + str;
        // return this.song.name + '-' + this.song.singers[0].name;
      }
    },
    watch: {
      song: {
        deep: true,
        handler(){
          this.initPlayer();
        }
      }
    },
    methods: {
      /** 显示播放器页面 */
      showPlayerPage(){
        this.$store.dispatch("setPlayerVisible", true);
      },
      /** 切换歌曲或初始化时： */
      initPlayer(){
        let that = this;
        that.isPlay = false;
        this.$refs.audio.load();
        this.$refs.audio.addEventListener('canplay', function(){
          that.$refs.audio.pause();
          that.$refs.audio.play();
          that.progressRun();
          that.isPlay = true;
          that.controlLock = false;
        });
        this.$refs.audio.addEventListener('ended', function(){
          that.$refs.audio.pause();
          that.playNext();
          return;
        });
      },
      /** 播放上一首 */
      playPrev(){
        if(this.controlLock)return;
        console.log('prev111');

        //正在播放的 是否在当前播放列表中
        if(this.$store.getters.isInCurrList) {

          console.log("prev");
          let index = this.$store.getters.currSongIndex;
          //判断当前播放列表的是否还有上一首,符合条件就播放上一首
          let list = this.$store.getters.currSongList;
          let prevIndex = index-1;
          if (prevIndex >= 0) {
            this.$store.dispatch("setSong", null); //先清空歌曲
            this.controlLock = true;
            //先获取歌曲资源的链接：
            let url = '';
            this.$axios.get(`/api/song/url?id=${list[prevIndex].id}`)
              .then(res => {
                url = res.data.data[0].url;
                //初始化下一首歌数据
                let prevSong = {};
                prevSong.url = url;
                prevSong.id = list[prevIndex].id;
                prevSong.name = list[prevIndex].name;
                prevSong.imgUrl = list[prevIndex].al.picUrl;
                prevSong.singers = list[prevIndex].ar;
                prevSong.index = prevIndex;
                this.$store.dispatch("setSong", prevSong);
                this.$store.dispatch("setCurrSongIndex", prevIndex);
                this.initPlayer();
              })
              .catch(err => console.log(err));
          }

        }
      },
      /** 播放下一首 */
      playNext(){
        if(this.controlLock)return;
        console.log('next111');

        //正在播放的 是否在当前播放列表中
        if(this.$store.getters.isInCurrList) {

          console.log("next");
          let index = this.$store.getters.currSongIndex;
          //判断当前播放列表的是否还有下一首,符合条件就自动播放下一首
          let list = this.$store.getters.currSongList;
          let nextIndex = index+1;
          if (list.length > nextIndex) {
            this.controlLock = true;
            //先获取歌曲资源的链接：
            let url = '';
            this.$axios.get(`/api/song/url?id=${list[nextIndex].id}`)
              .then(res => {
                url = res.data.data[0].url;
                //初始化下一首歌数据
                let nextSong = {};
                nextSong.url = url;
                nextSong.id = list[nextIndex].id;
                nextSong.name = list[nextIndex].name;
                nextSong.imgUrl = list[nextIndex].al.picUrl;
                nextSong.singers = list[nextIndex].ar;
                nextSong.index = nextIndex;
                this.$store.dispatch("setSong", nextSong);
                this.$store.dispatch("setCurrSongIndex", nextIndex);
                this.initPlayer();
              })
              .catch(err => console.log(err));
          }

        }
      },
      /** 播放\暂停 */
      playOrPause(){
        if (this.controlLock === false){
          if (this.isPlay){
            this.$refs.audio.pause();
            this.isPlay = false;
          }else if (this.isPlay === false){
            this.$refs.audio.pause();
            this.$refs.audio.play();
            this.isPlay = true;
            this.progressRun();  //进度条开始
          }
        }
        return;
      },
      /** 动态进度条 */
      progressRun(){
        let controlData = {};
        const music = this.$refs.audio;
        controlData.duration = music.duration;
        let that = this;
        
        music.addEventListener("timeupdate", function() {
          controlData.curTime = music.currentTime;
          const number = music.currentTime/music.duration;
          let perNumber = (number*100).toFixed(2);
          if(perNumber >= 100){
            that.currProgress = 0;
            that.isPlay = false;
          }
          controlData.currProgress = perNumber;
          that.$store.dispatch("setSongControl", controlData);
          perNumber += '%';
          that.currProgress = perNumber;
        })
      },
      /** 打开当前播放列表 */
      showCurrList(){
        if(this.$store.getters.currSongListVisible){
          this.$store.dispatch("setCurrSongListVisible", false);
        }else {
          this.$store.dispatch("setCurrSongListVisible", true);
        }
      }

    },
    mounted() {
      this.initPlayer();
    }
  }
</script>

<style scoped lang="scss">
  .music-player-mini{
    width: 100%;
    height: 60px;
    color: white;
    background: $dark-gradient-backgroud;
    position: fixed;
    bottom: 0;
    z-index: 999;
    .container{
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .song-img{
        width: 80px;
        height: 80px;
        margin-bottom: 30px;
        background: $gray-color;
        border-radius: 50%;
        overflow: hidden;
        img{
          width: 100%;
          height: 100%;
          animation: 18s img-rotate linear infinite;
          animation-play-state: running;
        }
        @keyframes img-rotate {
          0%{transform: rotate(0deg)}
          100%{transform: rotate(360deg)}
        }
      }
      .middle{
        width: 60vw;
        height: 60px;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        align-items: flex-end;
        .progress{
          width: 100%;
          height: 5px;
          border: 1px solid #29a19c;
          border-radius: 5px;
          position: relative;
          overflow: hidden;
          .current-progress{
            height: 100%;
            border-radius: 5px;
            background: lightblue;
            position: absolute;
          }
        }
        .bottom{
          width: 100%;
          display: flex;
          justify-content: space-between;
          .info{
            max-width: 60%;
            font-size: 0.2rem;
            display: flex;
            align-items: center;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
          .control{
            width: 80px;
            height: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .prev{
              width: 20px;
              height: 20px;
              background-image: url("./../assets/prev.svg");
              background-size: cover;
            }
            .play{
              width: 20px;
              height: 20px;
              background-image: url("./../assets/play.svg");
              background-size: cover;
            }
            .stop{
              width: 20px;
              height: 20px;
              background-image: url("./../assets/stop.svg");
              background-size: cover;
            }
            .next{
              width: 20px;
              height: 20px;
              background-image: url("./../assets/next.svg");
              background-size: cover;
            }
          }
        }
      }
      .list{
        width: 40px;
        position: relative;
      }
      .list::after{
        content: '';
        width: 30px;
        height: 4px;
        border-radius: 5px;
        background: white;
        position: absolute;
        top: 0;
        left: 10px;
        box-shadow: 0px -12px 0px 0px white, 0px 12px 0px 0px white;
      }
      .curlist-enter-active{
        animation: upAni 0.6s;
      }
      .curlist-leave-active{
        animation: downAni 0.6s;
      }
      @keyframes upAni {
        0%{
          transform: translateY(100vh);
        }
        100%{
          transform: translateY(0);
        }
      }
      @keyframes downAni {
        0%{
          transform: translateY(0);
        }
        100%{
          transform: translateY(100vh);
        }
      }
    }
    .music-audio{
      display: none;
    }
  }
</style>